package ThreadDemo;

/*
 * Author: JacksonCoder
 * FileName: PingPonglockingQueue
 * Version: 1.0.0
 * Date: 2025/5/14
 */

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class PingPongBlockingQueue {

    private final BlockingQueue<Integer> pingQ = new ArrayBlockingQueue<>(1);
    private final BlockingQueue<Integer> pongQ = new ArrayBlockingQueue<>(1);

    public PingPongBlockingQueue() throws InterruptedException {
        // 初始化先让 pingQ 有一个元素， 以便 ping 先打印
        pingQ.put(0);
    }

    public void ping() throws InterruptedException {
        pingQ.take();
        System.out.println("ping");
        pongQ.put(0);
    }

    public void pong() throws InterruptedException {
        pongQ.take();
        System.out.println("pong");
        pingQ.put(0);
    }

    // main
    public static void main(String[] args) throws InterruptedException {
        PingPongBlockingQueue pp = new PingPongBlockingQueue();

        Thread t1 = new Thread(() -> {
            try{
                for(int i = 0; i < 10; i++){
                    pp.ping();
                }
            }catch (InterruptedException e){
                Thread.currentThread().interrupt();
            }
        });

        Thread t2 = new Thread(() -> {
            try{
                for(int i = 0; i < 10; i++){
                    pp.pong();
                }
            }catch (InterruptedException e){
                Thread.currentThread().interrupt();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

    }

}
